package m.jclecai.com.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.adapter.BetJczqAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.dialog.BettingDialogFragment;
import m.jclecai.com.dialog.ShowOrderDialog;
import m.jclecai.com.listener.ISelectPlayListener;
import m.jclecai.com.listener.MyNotifyTextViewSetChanged;
import m.jclecai.com.utils.CalculateBetNums;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.StringUtils;
import m.jclecai.com.utils.Utils;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static m.jclecai.com.utils.Utils.ZQ_ITEM_LIST;

public class BettingJCZQActivity extends BaseActivity implements MyNotifyTextViewSetChanged, View.OnClickListener, ISelectPlayListener {

    @BindView(R.id.iv_pull_bg)
    ImageView ivPullBg;
    @BindView(R.id.tv_mid_title)
    TextView tv_mid_title;
    @BindView(R.id.rl_bar)
    RelativeLayout rl_bar;
    @BindView(R.id.include_term_stop_time)
    TextView include_term_stop_time;
    @BindView(R.id.include_listview)
    ListView include_listview;
    @BindView(R.id.include_bet_way)
    TextView include_bet_way;
    @BindView(R.id.include_multiple_context)
    EditText include_multiple_context;
    @BindView(R.id.toolbar_confirm)
    TextView toolbar_confirm;
    @BindView(R.id.tv_bonus)
    TextView tv_bonus;
    //奖金优化；
    @BindView(R.id.tv_bonus_optimize)
    TextView tv_bonus_optimize;

    //这里是最新的奖金优化
    @BindView(R.id.ll_bonus_optimize)
    LinearLayout ll_bonus_optimize;

    @BindView(R.id.cb_saidan)
    CheckBox mCbBox;

    //注数
    int voteNums;
    //倍数
    String multiple;
    //是否有默认值要选中
    boolean check = true;
    //要选中的默认值过关方式
    private String pass = "";
    //当前选中的过关方式 默认0为第一个
    private int currentDialoItemCheck = 0;
    BetJczqAdapter adapter;
    //详情见arrays.xml 对应 jczq_types_list 用于ui区分
    int pager = 0;
    int buyMoney = 0;
    //奖金优化
    String vote, name;
    private ShowOrderDialog mShowOrderDialog;

    int itemCount = Utils.ZQ_ITEM_LIST.size();//过关串数

    @Override
    public int getContentView() {
        return R.layout.activity_betting_jczq;
    }

    private String mSlogan;
    private String mWrate;
    private String mSunOrderMode;


    @Override
    public void initView() {
        Intent intent = getIntent();
        pager = intent.getIntExtra("pager", 0);
        name = intent.getStringExtra("name");

        setTitle(name);
        leftOptionText("添加");
        rightOptionText("发起合买");


        mShowOrderDialog = new ShowOrderDialog(this, new ShowOrderDialog.OnClickButtonListener() {

            @Override
            public void onClickSure(String mode, String profit, String slogan) {
                //确定;
                mSlogan = slogan;
                mWrate = profit;
                mSunOrderMode = mode;
                pay();
            }

            @Override
            public void onClickCancel() {
                //取消；
                mCbBox.setChecked(false);
            }
        }, "10", "10");
    }

    @Override
    public void initData() {
        adapter = new BetJczqAdapter(this, pager, this);
        View inflate = View.inflate(this, R.layout.lottery_list_footer, null);
        inflate.findViewById(R.id.betting_item_footer_clear).setOnClickListener(this);
        inflate.findViewById(R.id.betting_item_footer_check).setOnClickListener(this);
        include_listview.addFooterView(inflate);
        //低版本 addFooterView需要在setAdapter前面
        include_listview.setAdapter(adapter);
        String[] names = getResources().getStringArray(R.array.lottery_pass_types_name_list);
        names = StringUtils.filterData(names, "串", getItemCount(), adapter.getCheckDan(), isDG());
        //默认选中的过关方式
        if (names != null && names.length > 0) {
            pass = names[names.length - 1];
        } else {
            if (isDG()) {
                pass = "单关";
            } else {
                pass = "2串1";
            }
        }
        include_bet_way.setText(pass.replaceAll("1串1", "单关"));
        getPredictBonus();
    }

    //过关串数
    public int getItemCount() {
        itemCount = Utils.ZQ_ITEM_LIST.size();
        //含有比分玩法的，场次超过4场，最大过关 必须变成 4串1
        //含有半全场玩法的，场次超过4场，最大过关 必须变成 4串1
        //含有进球数玩法的，场次超过6场，最大过关 必须变成 6串1
        if (Utils.ZQ_ITEM_LIST.size() >= 4) {
            if (Utils.ZQ_ITEM_LIST.size() >= 6) {
                for (int i = 0; i < Utils.ZQ_ITEM_LIST.size(); i++) {
                    if (Utils.ZQ_ITEM_LIST.get(i).getMap().containsKey("2")) {
                        itemCount = 6;
                    }
                }
            }
            for (int i = 0; i < Utils.ZQ_ITEM_LIST.size(); i++) {
                if (Utils.ZQ_ITEM_LIST.get(i).getMap().containsKey("3") || Utils.ZQ_ITEM_LIST.get(i).getMap().containsKey("4")) {
                    itemCount = 4;
                }
            }
        }
        return itemCount;
    }

    //过关倍数
    @OnTextChanged(R.id.include_multiple_context)
    void multiple(Editable s) {
        Log.e("bs", s.toString());
        if (TextUtils.isEmpty(include_multiple_context.getText().toString())) {
            return;
        }
        if ("0".equals(s.toString())) {
            include_multiple_context.setText("1");
            include_multiple_context.setSelection(1);
            getPredictBonus();
            return;
        }
        getPredictBonus();
    }

    @OnClick({R.id.cb_saidan, R.id.toolbar_confirm})
    void onClickShowOrder() {
        if (TextUtils.isEmpty(pass)) {
            MyToast.showToast(getBaseContext(), "请选择过关方式");
            return;
        }
        if (TextUtils.isEmpty(include_multiple_context.getText().toString())) {
            include_multiple_context.setText("1");
            include_multiple_context.setSelection(1);
            getPredictBonus();
        }
        //这里表示点击的了显示跟单；
        mShowOrderDialog.show(buyMoney + "", (buyMoney / Integer.parseInt(multiple)) + "");
    }

    //过关方式
    @OnClick(R.id.include_bet_way)
    void showPassType() {
        if (Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()) {
            MyToast.showToast(this, "至少选择2场比赛");
            return;
        }

        BettingDialogFragment dialogFragment = new BettingDialogFragment();
        dialogFragment.show(getSupportFragmentManager(), "Dialog");
        dialogFragment.setItemCount(getItemCount());
        dialogFragment.setMinCount(adapter.getCheckDan());
        dialogFragment.setListener(this);
        dialogFragment.setDG(isDG());
        dialogFragment.setDefCheck(check, pass, currentDialoItemCheck);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.betting_item_footer_clear:
                if (ZQ_ITEM_LIST.size() > 0)
                    showAlertDialog("提示", "确认清空所有数据?", "取消", "确认", null, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ZQ_ITEM_LIST.clear();
                            adapter.notifyDataSetChanged();
                        }
                    });
                break;
            case R.id.betting_item_footer_check:
                startActivity(LotteryProtocolActivity.getIntent(this));
                break;
        }
    }

    //支付
//    @OnClick(R.id.toolbar_confirm)
    void pay() {
        if (TextUtils.isEmpty(pass)) {
            MyToast.showToast(getBaseContext(), "请选择过关方式");
            return;
        }
        /**
         * 此处提交之前先判断用户是否登录
         * 竞彩类 北京单场 只有混投调用balls  其余单关 混投奖金优化 其余奖金优化 其他栏目调用ball
         * 所以混合投注 做一个标识区分开减少判断逻辑
         *
         * 新增玩法单关玩法下
         * 如果过关方式仅仅只选择 单关 ==》 1*1  ball.php 单独过关方式
         * =================================================
         * 如果过关方式选择 单关,2*1,3*1 ==》 单关 =>1*1   balls.php 这里指其余过关方式
         * 如果过关方式选择 2*1,3*1 ==》   balls.php
         */
        String stringCode = StringUtils.getBonus(
                Utils.ZQ_ITEM_LIST, pass, (pager == 2 || pager == 6));
        Log.e("stringCode", stringCode);
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(voteNums));
        intent.putExtra(PAY_MULTIPLE, multiple);
        intent.putExtra(PAY_MONEY, String.valueOf(buyMoney));
        intent.putExtra(PAY_CODES, stringCode);
        Log.v("params", pass);
        try {
            intent.putExtra("num", pass.replace("*", ","));
        }catch (Exception e){

        }
        Log.v("params", pass.replace("*", ","));
        intent.putExtra(PAY_TYPE, "jczq");
        intent.putExtra(PAY_PASS, pass.replaceAll("串", "*").replaceAll("单关", "1*1"));
        intent.putExtra(PAY_LOTTERY_TYPE, name);
        //是否调用balls 接口
        intent.putExtra(PAY_LOTTERY_BALLS, "混合投注".equals(name) || (name.contains("单关") && !"单关".equals(pass)));

        intent.putExtra(SUN_ORDER_MODE, mSunOrderMode);
        intent.putExtra(SUN_ORDER_SLOGAN, mSlogan);
        intent.putExtra(PAY_WRATE, mWrate);
        intent.putExtra(IS_SHOW_ORDER, "1");

        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    //奖金优化
    @OnClick(R.id.ll_bonus_optimize)
    void bonusOptimize() {
        if (TextUtils.isEmpty(pass)) {
            MyToast.showToast(getBaseContext(), "请选择过关方式");
            return;
        }
       /* if ("混合投注".equals(name)) {
            DisPlay("混合投注不支持奖金优化！！！");
            return;
        }*/
        String playType = getPlayType();
        String term = getTerm();
        String stringCode = StringUtils.getBonusAward(Utils.ZQ_ITEM_LIST, pass, (pager == 2 || pager == 6));
        startActivityForResult(new Intent(this, BonusOptimizationActivity.class)
                        .putExtra("codes", stringCode)
                        .putExtra("vote", vote)
                        .putExtra("pass", pass.replaceAll("串", "*").replaceAll("单关", "1*1"))
                        .putExtra("money", buyMoney)
                        .putExtra(PAY_LOTTERY_TYPE, name)
                        .putExtra(PAY_MULTIPLE, multiple)
                        .putExtra(PAY_VOTENUMS, String.valueOf(voteNums))
                        .putExtra(PAY_TYPE, "jczq")
                        .putExtra(PAY_TYPE_NUM, playType)
                        .putExtra(PAY_TERM, term)
                , Constant_Result.CLOSEPAGE);
    }

    /**
     * 这里是获取期号；
     *
     * @return
     */
    private String getTerm() {
        ZqItem zqItem = Utils.ZQ_ITEM_LIST.get(0);
        String term = zqItem.getCodes()[0];
        return term.substring(0, term.length() - 3);
    }


    Subscription mSubscribe;

    /**
     * 预测奖金
     */
    private void getPredictBonus() {
        if (Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()) {
            MyToast.showToast(this, "至少选择2场比赛");
            tv_bonus.setText("");
            include_bet_way.setText("过关方式");
            this.pass = "";
            return;
        }
        //算预测奖金
        //这里我们开一个子线程进行一个计算；

        //算预测奖金
        try {
            vote = StringUtils.getBonusCode(Utils.ZQ_ITEM_LIST);
            Log.e("getBonusCode", vote);
            if (TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)) {
                MyToast.showToast(getBaseContext(), "请选择过关方式");
                return;
            }
            if (mSubscribe != null) {
                //绑定前，先解绑
                if (mSubscribe.isUnsubscribed()) {
                    mSubscribe.unsubscribe();
                }
            }
            tv_bonus.setText("正在计算中...");

            //这里开启一个子线程处理；目前存在一个问题就是变量的同步问题；
            mSubscribe = Observable.just("233").map(new Func1<String, String>() {
                @Override
                public String call(String s) {

                    String buyType = pass.replaceAll("串", "*");
                    buyType = buyType.replaceAll("单关", "1*1");
                    CalculateBetNums calculateBetNums = new CalculateBetNums();
                    //得到的是注数

                    //得到的是注数
                    voteNums = calculateBetNums.getVoteNums(vote, buyType);
                    List<String> rebuildVote = CalculateBetNums.rebuildVote(vote, buyType);

                    String sp_max = calculateBetNums.getBonus(rebuildVote, 1, 1);//最大奖金
                    String sp_min = calculateBetNums.getBonus(rebuildVote, 0, 1);//最小奖金
                    multiple = include_multiple_context.getText().toString().trim();
                    int num = Integer.parseInt(multiple);

                    String money = "";
                    if (num * Float.parseFloat(sp_min) == (num * Float.parseFloat(sp_max))) {
                        money = num * Float.parseFloat(sp_min) + "";
                    } else {
                        float spMin = Float.parseFloat(sp_min);
                        float vMin = num * spMin;
                        String minStr = "";
                        String maxStr = "";
                        if (vMin == Float.POSITIVE_INFINITY || vMin == Float.NEGATIVE_INFINITY) {
                            minStr = "0.00";
                        } else {
                            minStr = vMin + "";
                        }

                        float vMax = num * Float.parseFloat(sp_max);

                        if (vMax == Float.POSITIVE_INFINITY || vMax == Float.NEGATIVE_INFINITY) {
                            maxStr = "0.00";
                        } else {
                            maxStr = vMax + "";
                        }

                        money = minStr + "~" + maxStr;
                    }

                    buyMoney = (voteNums * num * 2);
                    String txt = String.format(getString(R.string.jc_bonus_optimiiza), voteNums, num, buyMoney, money);
                    return txt;
                }
            }).subscribeOn(Schedulers.computation())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String txt) {
                            tv_bonus.setText(Html.fromHtml(txt));
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            throwable.printStackTrace();
                            MyToast.showToast(getBaseContext(), "计算异常");
                            tv_bonus.setText("计算异常");
                        }
                    });

        } catch (Exception e) {
            MyToast.showToast(getBaseContext(), "计算异常");
            e.printStackTrace();
        }

       /* try {
            vote = StringUtils.getBonusCode(Utils.ZQ_ITEM_LIST);
            Log.e("getBonusCode", vote);
            if (TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)) {
                MyToast.showToast(getBaseContext(), "请选择过关方式");
                return;
            }
            String buyType = pass.replaceAll("串", "*");
            buyType = buyType.replaceAll("单关", "1*1");
            CalculateBetNums calculateBetNums = new CalculateBetNums();
            //得到的是注数
            voteNums = calculateBetNums.getVoteNums(vote, buyType);
            List<String> rebuildVote = CalculateBetNums.rebuildVote(vote, buyType);
            String sp_max = getBonus(rebuildVote, 1, 1);//最大奖金
            String sp_min = getBonus(rebuildVote, 0, 1);//最小奖金
            multiple = include_multiple_context.getText().toString().trim();
            int num = Integer.parseInt(multiple);
            String money = (num * Float.parseFloat(sp_min)) + "~" + (num * Float.parseFloat(sp_max));
            buyMoney = (voteNums * num * 2);
            String txt = String.format(getString(R.string.jc_bonus_optimiiza), voteNums, num, buyMoney, money);
            tv_bonus.setText(Html.fromHtml(txt));

        } catch (Exception e) {
            MyToast.showToast(getBaseContext(), "计算异常");
            e.printStackTrace();
        }*/
    }

    //支持单关的小蓝点
    boolean isDG() {
        boolean isDG = false;
        for (int i = 0; i < ZQ_ITEM_LIST.size(); i++) {
            String value = ZQ_ITEM_LIST.get(i).getCodes()[19];
            int dValue = TextUtils.isEmpty(value) ? 0 : Integer.parseInt(value);
            StringBuilder sb = new StringBuilder();
            //解析成二进制串 支持单关标志1 不支持标志0
            String s = Integer.toBinaryString(dValue);
            //因为足球有5个玩法 计算顺序为
            //胜平负 让球胜平负 总进球 比分 半全场
            //  0         0        1     1     1
            //其中总进球 比分 半全场 永远支持单关
            //因为我是直接从左往右拆分二进制
            int num = 5 - s.length();
            //num 是需要补齐位数 默认补齐0 例如7 = 111  补齐为00111
            //所以左->右前两个玩法为0 不支持单关
            for (int j = 0; j < num; j++) {
                //补齐位数 默认补齐0
                sb.append("0");
            }
            sb.append(s);
            if (pager == 0 || pager == 1) {
                isDG = "1".equals(String.valueOf(sb.charAt(pager)));
            }
            if (pager == 2) {
                isDG = false;
            } else {
                isDG = true;
            }
//            isDG = !(pager == 0 || pager ==1) || "1".equals(String.valueOf(sb.charAt(pager)));
            if (!isDG) break;
        }
        return isDG;
    }

    @Override
    public void onClickSetChangedText() {
//        tv_bonus.setText("");
        this.pass = getItemCount() + "串1";
//        include_bet_way.setText(this.pass);
        adapter.notifyDataSetChanged();
        getPredictBonus();
    }

    @Override
    public void refreshData() {
//        tv_bonus.setText("");
//        include_bet_way.setText("过关方式");
        this.pass = getItemCount() + "串1";
        adapter.notifyDataSetChanged();
        include_bet_way.setText(this.pass);
        getPredictBonus();
    }

    @Override
    public void select(String value, int itemPosition) {
        currentDialoItemCheck = itemPosition;
        this.pass = value;
        check = !TextUtils.isEmpty(value);
        if (TextUtils.isEmpty(value)) {
            include_bet_way.setText("过关方式");
            tv_bonus.setText("");
        } else {
            include_bet_way.setText(value.replaceAll("1串1", "单关")
                    .replaceAll("[*]", "串"));
        }
        getPredictBonus();
    }


    //合买
    @OnClick(R.id.tv_right_option)
    void jointPurchase() {


        new AlertDialog.Builder(this)
                .setMessage("功能开发中...")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

        /*     if (Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()) {
            MyToast.showToast(this, "至少选择2场比赛");
            tv_bonus.setText("");
            include_bet_way.setText("过关方式");
            this.pass = "";
            return;
        }
        if (TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)) {
            MyToast.showToast(getBaseContext(), "请选择过关方式");
            return;
        }
        String stringCode = StringUtils.getBonus(Utils.ZQ_ITEM_LIST, pass, (pager == 2 || pager == 6));
        Intent intent = new Intent(this, JointPurchaseActivity.class);
        intent.putExtra("totalNum", voteNums);
        intent.putExtra("multiple", Integer.valueOf(multiple));
        intent.putExtra("totalMoney", buyMoney);
        intent.putExtra("num", 1);
        intent.putExtra(PAY_TYPE, "jczq");
        intent.putExtra(PAY_CODES, stringCode + ";");//因为JointPurchaseActivity code会-1
        intent.putExtra(PAY_NAME, "合买");
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);*/
    }

    @Override
    protected void close() {
        finish();
    }

    /**
     * 根据玩法来获取对应的playType
     *
     * @return
     */
    public String getPlayType() {
        //这里是需要修改玩法的类型的；

        if (name.equals("胜平负")) {

            return "41";

        } else if (name.equals("胜平负(让)")) {

            return "42";

        } else if (name.equals("混合投注")) {

            return "46";

        } else if ("半全场".equals(name)) {

            return "45";

        } else if ("总进球".equals(name)) {

            return "43";

        } else if ("单关".equals(name)) {

            return "47";
        } else if ("比分".equals(name)) {

            return "44";

        }

        return "jczq";
    }

}
